import pdfplumber
import requests
import json
import re
import random

# 接口地址
api_url = "http://192.168.11.63:32565/hazardous-waste/hazardous_waste_information"
# 请求头（保持原配置）
headers = {
    "Content-Type": "application/json",
    "authorization": "Basic c2FiZXI6c2FiZXJfc2VjcmV0",
    "cup-auth": "bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ0ZW5hbnRfaWQiOiIwMDAwMDAiLCJ1c2VyX25hbWUiOiIxMzYwODMzOTU1NyIsImRlcHRfaWRzIjoiMTgyMDM3OTg1ODM3OTY4MTc5MyIsInJlYWxfbmFtZSI6IkdPT0TlhYjnlJ8iLCJjbGllbnRfaWQiOiJzYWJlciIsInJvbGVfaWQiOiIxNjk2MDAxNDQwMDU3ODQzMDAyIiwic2NvcGUiOlsiYWxsIl0sIm9hdXRoX2lkIjoiIiwiZGVwdF90eXBlIjoiMiIsImV4cCI6MTc1OTIwNjQ2OSwicm9sZV9hbGlhcyI6ImNvbXBhbnksY29tcGFueUxlYWRlcixiaWdfcm9sZSIsImp0aSI6IjI3ZmE2Y2JlLTk3OTEtNDdkNy1iNjhlLTYwNTRiMDA2Y2VkOCIsImtleSI6ImN1cGJhc2UiLCJkZXB0X25hbWUiOiLnpo_lu7rkvJjlipvnibnmnZDmlpnmnInpmZDlhazlj7giLCJhdmF0YXIiOiIvZGVmLWJ1Y2tldC8yMDI1MDQwNy8xNzQzOTkzMzkwMDcyLmpwZyIsImF1dGhvcml0aWVzIjpbImNvbXBhbnlMZWFkZXIiLCJiaWdfcm9sZSIsImNvbXBhbnkiXSwicm9sZV9uYW1lIjoiY29tcGFueSxjb21wYW55TGVhZGVyLGJpZ19yb2xlIiwibGljZW5zZSI6InBvd2VyZWQgYnkgY3VweCIsImZ1bGxfbmFtZSI6Iuemj-W7uuS8mOWKm-eJueadkOaWmeaciemZkOWFrOWPuCIsInBvc3RfaWQiOiIxMTIzNTk4ODE3NzM4Njc1MjA4IiwidXNlcl9pZCI6IjE5MDcyODYxMTQ2MDYxNjYwMTgiLCJwaG9uZSI6IjEzNjA4MzM5NTU3Iiwibmlja19uYW1lIjoiR09PROWFiOeUnyIsImRldGFpbCI6eyJ0eXBlIjoid2ViIiwicmVhbE5hbWUiOiJHT09E5YWI55SfIn0sImRlcHRfaWQiOiIxODIwMzc5ODU4Mzc5NjgxNzkzIiwiYWNjb3VudCI6IjEzNjA4MzM5NTU3In0.kwbEs3f1ilbQoOzbiUiBq0UDcU0xTs3Ptq8NW1iC7ns"

}

# 危险特性映射字典
hazardous_feature_mapping = {
    "T": "toxicity",
    "C": "corrosivity",
    "I": "ignitability",
    "R": "reactivity",
    "In": "infectivity"
}

# 危废形态映射字典
hazardous_waste_state_mapping = {
    "固态": "solid_state",
    "半固态": "semisolid_state",
    "液态": "liquid_state",
    "气态": "gas_state"
}


def generate_random_string(length=8):
    """生成指定长度的随机字符串"""
    chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
    return ''.join(random.choice(chars) for _ in range(length))


def parse_pdf_waste_file(pdf_path):
    waste_data_list = []
    target_header = ["废物类别", "行业来源", "废物代码", "危险废物", "危险特性"]

    with pdfplumber.open(pdf_path) as pdf:
        for page_num, page in enumerate(pdf.pages):
            if page_num < 3:
                continue
            tables = page.extract_tables()
            for table in tables:
                for row in table:
                    if not any(cell.strip() for cell in row if cell is not None):
                        continue
                    row_clean = [cell.strip() if cell is not None else "" for cell in row]
                    if row_clean[:5] == target_header:
                        continue
                    if len(row_clean) < 5:
                        continue

                    # 废物类别（提取HW**部分）
                    waste_category_match = re.search(r"HW\d+", row_clean[0])
                    waste_category = waste_category_match.group() if waste_category_match else ""
                    # 详细说明（行业来源列）
                    detail_desc = row_clean[1]
                    # 废物代码
                    waste_code = row_clean[2]
                    # 危险废物（用于危废名称和物理性状）
                    hazardous_waste = row_clean[3]
                    # 危险特性代码
                    hazardous_feature_codes = row_clean[4]

                    if not waste_code.strip() or not hazardous_waste.strip():
                        continue

                    # 生成不重复的危废名称（类别名称 + 随机字符串）
                    waste_name = f"{waste_category}_{generate_random_string()}"
                    # 所属企业ID（指定）
                    enterprise_id = "1820379858379681793"  # 替换为实际企业ID
                    # 物理性状（危险废物列内容）
                    physical_properties = hazardous_waste
                    # 随机选取危废形态
                    waste_state_key = random.choice(list(hazardous_waste_state_mapping.keys()))
                    waste_state = hazardous_waste_state_mapping[waste_state_key]
                    # 转换危险特性为英文
                    hazardous_features = []
                    for code in hazardous_feature_codes:
                        if code in hazardous_feature_mapping:
                            hazardous_features.append(hazardous_feature_mapping[code])
                    hazardous_feature = ",".join(hazardous_features).lower()

                    waste_data = {
                        "wasteName": waste_name,
                        "wasteCode": waste_code,
                        "wasteCategory": waste_category,
                        "hazardousFeature": hazardous_feature,
                        "wasteState": waste_state,
                        "detailDesc": detail_desc,
                        "physicalProperties": physical_properties,
                        "enterpriseId": "1820379858379681793"
                    }
                    waste_data_list.append(waste_data)

    # 去重（根据废物代码）
    unique_waste_data = []
    seen_codes = set()
    for data in waste_data_list:
        if data["wasteCode"] not in seen_codes:
            seen_codes.add(data["wasteCode"])
            unique_waste_data.append(data)

    return unique_waste_data


def insert_data_via_api(waste_data_list):
    success_count = 0
    fail_count = 0
    fail_details = []
    for data in waste_data_list:
        try:
            response = requests.post(
                api_url,
                data=json.dumps(data),
                headers=headers
            )
            resp_json = response.json()
            if response.status_code in (200, 201) and resp_json.get("success"):
                success_count += 1
            else:
                fail_count += 1
                fail_details.append({
                    "data": data,
                    "status_code": response.status_code,
                    "response_text": response.text,
                    "resp_json": resp_json
                })
        except Exception as e:
            fail_count += 1
            fail_details.append({"data": data, "error": str(e)})
    return {"success_count": success_count, "fail_count": fail_count, "fail_details": fail_details}


if __name__ == "__main__":
    pdf_file_path = r"C:\Users\Administrator\Downloads\危废目录.pdf"
    try:
        waste_data = parse_pdf_waste_file(pdf_file_path)
        print(f"从 PDF 解析出 {len(waste_data)} 条有效危废数据（已去重）")
        if waste_data:
            result = insert_data_via_api(waste_data)
            print(f"\n接口插入完成：")
            print(f"成功条数：{result['success_count']}")
            print(f"失败条数：{result['fail_count']}")
            if result["fail_count"] > 0:
                print(f"\n失败详情（前10条）：")
                for fail in result["fail_details"][:10]:
                    print(
                        f"  危废代码：{fail['data']['wasteCode']}，原因：{fail.get('error') or fail.get('response_text')}")
        else:
            print("未解析到任何有效危废数据，请检查PDF路径或格式！")
    except Exception as e:
        print(f"解析PDF时发生错误：{str(e)}")